'use strict';

const path = require('path');
const { BrowserWindow, Notification } = require('electron');
const { getMainWindow } = require('ee-core/electron');
const { isDev, isProd, getElectronDir, getBaseDir } = require('ee-core/ps');
const { getConfig } = require('ee-core/config');
const { isFileProtocol } = require('ee-core/utils');
const { logger } = require('ee-core/log');

/**
 * Window
 * @class
 */
class WindowService {

  constructor() {
    this.myNotification = null;
    this.windows = {}
  }

  /**
   * Create a new window
   */
  createWindow(args) {
    const { type, content, windowName, windowTitle } = args;
    let contentUrl = null;
    if (type == 'html') {
      contentUrl = path.join('file://', getBaseDir(), content)
    } else if (type == 'web') {
      contentUrl = content;
    } else if (type == 'vue') {
      let addr = 'http://localhost:8081'
      if (isProd()) {
        const { mainServer } = getConfig();
        if (isFileProtocol(mainServer.protocol)) {
          addr = mainServer.protocol + path.join(getBaseDir(), mainServer.indexPath);
        } else {
          addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
        }
      }
      contentUrl = addr + content;
    }     
    logger.info('[createWindow] ', windowName, contentUrl);
    const opt = {
      title: windowTitle,
      show: false, //先隐藏窗口，在加载完页面后再显示
      width: args.windowWidth || 800,
      height: args.windowHeight || 600,
      x: args.windowX || Math.floor(Math.random()*400),
      y: args.windowY || Math.floor(Math.random()*200),
	    frame: args.windowFrame || true, // 默认无边框
      resizable: args.resizable || false,
      autoHideMenuBar: args.windowHideMenuBar || false, // 隐藏菜单栏，默认为false
      titleBarStyle: args.windowTitleBarStyle || "default",
      titleBarOverlay: args.windowTitleBarOverlay || false,//隐藏标题栏后悬浮按钮
      closable: args.windowClosable || true,
      alwaysOnTop : args.windowAlwaysOnTop || false ,//窗口置顶
      webPreferences: {
        webviewTag: true,
        webSecurity: false,
        allowRunningInsecureContent: true, // 允许运行不安全的内容
        nodeIntegration: true,
        devTools: isDev ? true : false,
      },
    }
	  if(args.isContextIsolation){
        opt.webPreferences.contextIsolation = true; //是否启用上下文隔离
        opt.webPreferences.preload = path.join( getElectronDir(), 'preload', 'bridge.js');
    }else{
        opt.webPreferences.contextIsolation = false;        
    }
	  if (args.isModal) {
        opt.modal = true;
        opt.parent = getMainWindow();
    }
    const win = new BrowserWindow(opt);
    const winContentsId = win.webContents.id;
    win.loadURL(contentUrl);
    if (isDev()) {
      // win.webContents.openDevTools();
    }
	 win.once("ready-to-show", () => {
      if(args.isCenter) { 
        win.center();
      }
      win.setTitle(windowTitle);
      win.focus();
      win.show();
    });
    this.windows[windowName] = win;
    // logger.info("\nAll windows .......................\n",this.windows);
    return winContentsId;
  }
  
  /**
   * Get window contents id
   */
  getWCid(args) {
    const { windowName } = args;
    let win;
    if (windowName == 'main') {
      win = getMainWindow();
    } else {
      win = this.windows[windowName];
    }
    
    return win.webContents.id;
  }

  /**
   * Realize communication between two windows through the transfer of the main process
   */
  communicate(args) {
    const { receiver, content } = args;
    if (receiver == 'main') {
      const win = getMainWindow();
      win.webContents.send('controller/sms/subToMain', content);
    } else {
      const win = this.windows[receiver];
      win ? win.webContents.send('controller/sms/mainToSub', content)
        : logger.warn(`[communicate] window ${receiver} not found`);
    }
  }  

  /**
   * createNotification
   */
  createNotification(options, event) {
    const channel = 'controller/os/sendNotification';
    this.myNotification = new Notification(options);

    if (options.clickEvent) {
      this.myNotification.on('click', (e) => {
        let data = {
          type: 'click',
          msg: '您点击了通知消息'
        }
        event.reply(`${channel}`, data)
      });
    }

    if (options.closeEvent) {
      this.myNotification.on('close', (e) => {
        let data = {
          type: 'close',
          msg: '您关闭了通知消息'
        }
        event.reply(`${channel}`, data)
      });
    }

    this.myNotification.show();
  }

}
WindowService.toString = () => '[class WindowService]';

module.exports = {
  WindowService,
  windowService: new WindowService()
};  